﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace L4View.BusinessModel.SpyLogMonitor
{
    public class ManualFileSeeker : FileSeeker
    {
        private StreamReader _inStream;

        private ManualResetEvent _endReadEvent;

        private int _offset;

        private int _range;

        private StreamReader InStream
        {
            get
            {
                if (_inStream == null)
                    _inStream = File.OpenText(FileName);

                return _inStream;
            }
        }

        public override void SetOffset(int offset)
        {
            _offset = offset;
        }

        public override void SetRange(int range)
        {
            _range = range;                 
        }

        public override System.Threading.WaitHandle StartRead()
        {
            return _endReadEvent = new ManualResetEvent(false);    
        }

        protected override string Read()
        {
            if (_range == 0 )
            {
                _endReadEvent.Set();
                _endReadEvent = null;
                
                if ( _inStream != null )
                    _inStream.Close();
                _inStream = null;

                return null;
            }

            var buffer = new char[10];

            var readCount = InStream.Read(buffer, _offset, buffer.Length);

            if (readCount > 0)
            {
                _range -= buffer.Length;
                _range = _range < 0 ? 0 : _range;
            }
            else
                _range = 0;

            return buffer.ToString();
        }
    }
}
